<template>

    <div class="title-switch">
        <ul>
            <li @click="categoriesTypeActive = item.name; getNavListFun();" v-for="(item, index) in categoriesType"
                :key="index" :class="{ 'switch-active': item.name === categoriesTypeActive }">{{ item.name }}
            </li>
        </ul>
        <div class="title-switch-btn">
            <div class="add-box" @click="addNavDialogShow = true">
                <client-only>
                    <el-icon>
                        <Plus />
                    </el-icon>
                </client-only>
                添加
            </div>
        </div>
    </div>
    <ul class="site_tab_items" v-show="categoriesTypeActive === '最近使用'">
        <li v-for="(item, index) in recentlyUsedList.slice(0, 7)" :key="index">
            <a :href="item.link" target="blank">
                <el-skeleton :loading="recentlyUsedListLoading" animated :throttle="{ leading: 500, initVal: true }">
                    <template #template>
                        <el-skeleton-item variant="image" style="width: 24px;height:24px" />
                    </template>
                    <template #default>
                        <img :src="item.imageUrl" style="width: 24px;height:24px">
                    </template>
                </el-skeleton>
                <el-tooltip class="box-item" popper-class="box-item" style="width: 200px" effect="dark"
                    placement="bottom">
                    <template #content>
                        <div>{{ item.name }}</div>
                    </template>
                    <span class="_text_over_hidden_">{{ item.name }}</span>
                </el-tooltip>

            </a>
        </li>
        <li v-if="recentlyUsedList.length === 0" class="no-data">
            <span>暂无使用数据,快去发现精彩内容吧!</span>
        </li>
    </ul>
    <ul class="site_tab_items" v-show="categoriesTypeActive === '我的导航'">
        <li v-for="(item, index) in categories?.length > 7 ? categories.slice(0, 7) : categories" :key="index">
            <a :href="item.linkUrl" target="blank">
                <img :src="item.iconUrl" style="width: 24px;height:24px">
                <el-tooltip class="box-item" popper-class="box-item" style="width: 200px" effect="dark"
                    placement="bottom">
                    <template #content>
                        <div>{{ item.name }}</div>
                    </template>
                    <span class="_text_over_hidden_">{{ item.name }}</span>
                </el-tooltip>
            </a>
        </li>
        <li v-if="categories?.length === 0" class="no-data">
            <span>暂无使用数据,快去发现精彩内容吧!</span>
        </li>
    </ul>
    <el-dialog v-model="addNavDialogShow" title="设置我的导航" width="500">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="地址" prop="name">
                <div style="display: flex;align-items: center;width: 100%;">
                    <el-input style="flex:1" v-model="form.url" placeholder="请输入http或https开头的网址" />
                    <el-button @click="getUrl(form.url)" style="margin-left: 10px">自动获取</el-button>
                </div>
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="排序" prop="name">
                <el-input v-model.number="form.sort" placeholder="请输入排序" />
            </el-form-item>
            <el-form-item label="图标" prop="name">
                <el-upload action="#" :http-request="requestUpload" :show-file-list="false"
                    :before-upload="beforeUpload">
                    <img v-if="imgUrl" :src="imgUrl" alt="" class="form-upload-img">
                    <el-button>
                        {{ imgUrl ? '更改' : '新增' }}
                    </el-button>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addNavDialogShow = false">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    添加
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { getRecentlyUsedList, getHomeNav } from '@/api/homePage';
import { Plus } from '@element-plus/icons-vue';
import {
  getNavList, addNav
} from "@/api/user";
import { defineExpose } from 'vue'

import { useUserStore } from './../stores/user'

onMounted(() => {
    getRecentlyUsedListFun();
})

const categoriesType = ref([{
  name: '最近使用',
}, {
  name: '我的导航',
}])

const categoriesTypeActive = ref('最近使用');
const categories = ref([])

const addNavDialogShow = ref(false);// 新增导航栏弹窗

const form = ref({
    "siteType": '1',
    "name": "",
    "url": "",
    "logoFileId": "",
    "sort": 0
})

const fileList = ref([]);
const imgUrl = ref(null);

/** 覆盖默认上传行为 */
function requestUpload() {
}

// 解析url
const getUrl = async (url) => {
    const res = await commonUrlFavicon({ url: url });
    imgUrl.value = 'data:image/png;base64,' + res.data.b64;
    form.value.name = res.data.title;
    // 先转为blob
    let blob = dataURLtoBlob('data:image/png;base64,' + res.data.b64);
    // 拿到文件名
    let fileName = form.value.name;
    // 2，在转为 file类型
    fileList.value = blobToFile(blob, fileName);
    uploadImg();
}

//1,先将base64转换为blob
const dataURLtoBlob = (dataurl) => {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

//2,再将blob转换为file
const blobToFile = (theBlob, fileName) => {
    theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
    theBlob.name = fileName;                // 文件名
    return new File([theBlob], fileName, { type: theBlob.type, lastModified: Date.now() });
}


/** 上传预处理 */
const beforeUpload = (file) => {
    if (file.type.indexOf("image/") == -1) {
        proxy.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    } else {
        fileList.value = file;
        imgUrl.value = URL.createObjectURL(file);
        uploadImg();
    }
}

/** 上传图片 */
const uploadImg = () => {
    let formData = new FormData();
    formData.append("file", fileList.value);
    uploadFile(formData).then(response => {
        form.value.logoFileId = response.data;
    });
}


// 提交我的导航
const submitForm = () => {
    addNav(form.value).then(res => {
        if (res.suc) {
            addNavDialogShow.value = false;
            getNavListFun();
            ElNotification({
                title: '提交成功',
                type: 'success',
            })
        } else {
            ElNotification({
                title: '提交失败',
                type: 'error',
            })
        }
    })
}

// 未登录 我的导航
const getHomeNavFun = () => {
  getHomeNav().then(res => {
    categories.value = [];
    res.data?.categories?.forEach(item => {
      categories.value = [...categories.value, ...item.items]
    })
  })
}
// const getHomeNavData = await getApi('/home/nav');
// categories.value = getHomeNavData.data?.categories;


// 获取登陆后我的导航列表
const getNavListFun = () => {
    if (useUserStore().token) {
        getNavList().then(res => {
            categories.value = [];
            res.data?.categories?.forEach(item => {
                categories.value = [...item.items]
            })
        })
    } else {
        getHomeNavFun();
    }
}

// 最近使用
const recentlyUsedList = ref([]);
const recentlyUsedListLoading = ref(true);

const getRecentlyUsedListFun = () => {
    getRecentlyUsedList().then(res => {
        recentlyUsedList.value = res.data;
        recentlyUsedListLoading.value = false;
    })
}

// const recentlyUsedListData = await getApi('/home/recently-used/list');
// recentlyUsedList.value = recentlyUsedListData.data;

watch(
    () => useUserStore().token,
    (newRoute) => {
        getNavListFun();
    },
    { deep: true, immediate: false }
);

// 暴露方法给父组件
defineExpose({
    getRecentlyUsedListFun
})

</script>

<style scoped></style>
